var accountRelationId=sessionStorage.getItem("accountRelationId")
var mainCustomerIds=""
var customerId=""
var orderaccountarr=[]//下单账号
var orderaccount={}
var settlementaccountarr=[]//结算账号
var settlementaccount={}
var approvalaccountarr=[]//审批账号
var approvalaccount={}
var approvalorders=0//审批顺序交互
var updataapprovalorder=""
var approveSeqss=""
var isOrSigndt='';
//修改账号关联
modifyaccount()
function modifyaccount() {
    $.ajax({
        url:root.member.getDetail,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        async:false,//优先运行
        data:{
            "accountRelationId":accountRelationId,
        },
        success: function (data) {
            var modifydata=data.data
            customerId=modifydata.customerId
            mainCustomerIds=modifydata.mainCustomerId
            $("#customerName").html(modifydata.customerName)
            //下单账号渲染
            if(modifydata.orderAccountDto!=""||modifydata.orderAccountDto!=null){
                $("#orderaccountadd").html(modifydata.orderAccountDto.loginAccount)


                orderaccount = {
                    "memberId": modifydata.orderAccountDto.memberId
                }
                orderaccountarr.push(orderaccount)
                //改变高亮显示
                $("#adds").removeClass("add-one")
                $("#deletes").removeClass("delete-one")
                $("#adds").addClass("add2-one")
                $("#deletes").addClass("delete2-one")
                $("#adds").removeAttr("onclick");
                $("#deletes").attr("onclick", "orderaccountdelete(1)")
            }else {
                $("#orderaccountadd").html("")
                $("#adds").removeClass("add2-one")
                $("#deletes").removeClass("delete2-one")
                $("#adds").addClass("add-one")
                $("#deletes").addClass("delete-one")
                $("#adds").attr("onclick","orderaccountadd(1)")
                $("#deletes").removeAttr("onclick");
            }
           //审批账号渲染
            var approvalhtml=""
            var approvalaccounts= '';
            if(modifydata.approveAccountDtos!=""||modifydata.approveAccountDtos!=null){

                updataapprovalorder=modifydata.approveAccountDtos
                $("#deletes2").removeClass("delete-one")
                $("#deletes2").addClass("delete2-one")
                $("#deletes2").attr("onclick","orderaccountdelete(2)")
              for(var i = 0; i < modifydata.approveAccountDtos.length; i++) {
                  approvalaccount = {
                      "memberId": modifydata.approveAccountDtos[i].memberId,
                  }
                  approvalaccountarr.push(approvalaccount)

                  //表格渲染
        if(modifydata.approveAccountDtos[i].approveSeq==0){
        approveSeqss=""
        }else {
          approveSeqss=modifydata.approveAccountDtos[i].approveSeq
        }
                  if(approveSeqss){//审批顺序值
                    $("#civil").prop('checked', true)
                    if(modifydata.approveAccountDtos[i].isApprove==20){
                        isOrSigndt =modifydata.approveAccountDtos[i].isOrSign
                        approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" value="'+approveSeqss+'" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" checked="true" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony "><span>订单金额</span>< <span><input value="'+modifydata.approveAccountDtos[i].orderMoneyLimit+'" style="width: 64px;"  class="motyval"  oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
                    }else{
                        isOrSigndt =modifydata.approveAccountDtos[i].isOrSign
                        approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" value="'+approveSeqss+'" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input value="'+modifydata.approveAccountDtos[i].orderMoneyLimit+'"  style="width: 64px;"  class="motyval"  oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
                    }
                  }else {
                    if(modifydata.approveAccountDtos[i].isOrSign==0){
                        $("#huoqian").prop('checked', false)
                        isOrSigndt =modifydata.approveAccountDtos[i].isOrSign
                        approvalhtml='<span class="approval-orderxu">--</span>'
                    }else {
                      $("#huoqian").prop('checked', true)
                      isOrSigndt = modifydata.approveAccountDtos[i].isOrSign
                      approvalhtml='<span class="approval-orderxu">--</span>'

                    }
                      
                  }


                  approvalaccounts+=' <li class="every-approval">' +
                      '<input class="checkbox selection" onclick="accountid(this)" type="checkbox" value='+modifydata.approveAccountDtos[i].memberId+'>' +
                      ' <span class=" accountnumber">'+modifydata.approveAccountDtos[i].loginAccount+'</span><span class=" accountnumber2" style="display: none">'+modifydata.approveAccountDtos[i].memberId+'</span>' +
                      '<span class="approvalorder">'+approvalhtml+'</span>' +
                      '</li>'


              }
                $(".approvalaccounts").append(approvalaccounts)
               if(approvalaccountarr.length>9){
                   $("#adds2").removeClass("add-one")
                   $("#adds2").addClass("add2-one")
                   $("#adds2").removeAttr("onclick");
               }
           }

          //结算账号渲染
          $(".webselment").each(function(i,item){
            if(modifydata.settleAccountDto.settleType == $(item).val()){
                $(item).prop('checked',true)
            }
        })
           if(modifydata.settleAccountDto!=""||modifydata.settleAccountDto!=null){
               $("#settlementaccount").html(modifydata.settleAccountDto.loginAccount)
               settlementaccount = {
                   "memberId": modifydata.settleAccountDto.memberId,
                   "settleType":''

               }
               settlementaccountarr.push(settlementaccount)
               //改变高亮显示
               $("#adds3").removeClass("add-one")
               $("#deletes3").removeClass("delete-one")
               $("#adds3").addClass("add2-one")
               $("#deletes3").addClass("delete2-one")
               $("#adds3").removeAttr("onclick");
               $("#deletes3").attr("onclick", "orderaccountdelete(3)")
           }
       },
       error: function () {
           $.Huimodalalert('失败！',2000);
       }
   });
}


//账号
myFunctionaa()
function myFunctionaa(){
   $.ajax({
       url:root.member.getMembers,
       cache: false,  //禁用缓存
       type: "POST",
       dataType:'json',
       contentType: "application/json",
       data: JSON.stringify({
           "pageNum":1,
           "pageSize":5000,
           "loginAccount":$("#organization_name").val(),
           "mobilePhone":"",
           "employUser":"",
           "status":"",
           "mainCustomerId":mainCustomerIds,
       }),
       success: function (data) {
           if(data.errorCode=="0"){
               var jsonObj =data.data.data;
               $("#tuankd").html("");
               if(jsonObj==""){
                   $("#tuankd").html("<li>无数据</li> ");
               }else {
                   var optionstring = "";
                   for (var  i= 0; i < jsonObj.length; i++) {
                       optionstring += "<li class='dda' onclick='relationd("+ jsonObj[i].memberId+",\""+jsonObj[i].loginAccount+"\")' data-align=\"" + jsonObj[i].memberId + "\" > " + jsonObj[i].loginAccount + "</li>";
                   }
                   $("#tuankd").html(optionstring);
                   $(".kehus").animate({scrollTop:"0"},1);
                   $("#tuankd").show()


               }
           }else{
               $("#tuankd").html("<li>无数据</li> ");
           }

       },
       error: function () {
           $.Huimodalalert('失败！',2000);
       }
   });

}

function relationd(id,ce) {
   $("#organization_name").val(ce).text(id)
   $("#tuankd").show()
}

function orderaccountadd(val){
   if(val==1){
       //下单账号添加
       //赋值
       if($("#organization_name").text()!=""&&$("#organization_name").val()!="") {
           $("#orderaccountadd").html($("#organization_name").val())
           orderaccount = {
               "memberId": $("#organization_name").text()
           }
           orderaccountarr.push(orderaccount)
           //改变高亮显示
           $("#adds").removeClass("add-one")
           $("#deletes").removeClass("delete-one")
           $("#adds").addClass("add2-one")
           $("#deletes").addClass("delete2-one")
           $("#adds").removeAttr("onclick");
           $("#deletes").attr("onclick", "orderaccountdelete(1)")
           $("#organization_name").val("")
           $("#organization_name").text("")
       }
   }else if (val==2) {
      //审批账号添加
       if($("#organization_name").text()!=""&&$("#organization_name").val()!=""){
           $("#deletes2").removeClass("delete-one")
           $("#deletes2").addClass("delete2-one")
           $("#deletes2").attr("onclick","orderaccountdelete(2)")

           approvalaccount={
               "memberId":$("#organization_name").text(),
           }
           //去重
           for (let j=0;j<approvalaccountarr.length;j++) {
               if ($("#organization_name").text() == approvalaccountarr[j].memberId){
                   $.Huimodalalert('不能添加重复数据！',2000);
                   return false;
               }
           }
           approvalaccountarr.push(approvalaccount)
               if(approvalaccountarr.length>19){
                   $("#adds2").removeClass("add-one")
                   $("#adds2").addClass("add2-one")
                   $("#adds2").removeAttr("onclick");
               }

           var approvalhtml=""
           if(approvalorders==0){
               if($("#civil").is(':checked')==true){
                   approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input class="motyval"  style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
               }else {

                   approvalhtml='<span class="approval-orderxu">--</span>'
               }
           }else {
               approvalhtml='<span>审批顺序</span><input type="text" id="approvalinput" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input class="motyval"  style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
           }
           var approvalaccounts= '';
           approvalaccounts+=' <li class="every-approval">' +
               '<input class="checkbox selection" onclick="accountid(this)" type="checkbox" value='+$("#organization_name").text()+'></span>' +
               ' <span class=" accountnumber">'+$("#organization_name").val()+'</span><span class=" accountnumber2" style="display: none">'+$("#organization_name").text()+'</span>' +
               '<span class="approvalorder">'+approvalhtml+'</span>' +
             
               '</li>'

           $(".approvalaccounts").append(approvalaccounts)


           $("#organization_name").val("")
           $("#organization_name").text("")

       }


   }else if (val==3){
       //结算账号添加
       //赋值
       if($("#organization_name").text()!=""&&$("#organization_name").val()!="") {
           $("#settlementaccount").html($("#organization_name").val())
           settlementaccount = {
               "memberId": $("#organization_name").text()
           }
           settlementaccountarr.push(settlementaccount)
           //改变高亮显示
           $("#adds3").removeClass("add-one")
           $("#deletes3").removeClass("delete-one")
           $("#adds3").addClass("add2-one")
           $("#deletes3").addClass("delete2-one")
           $("#adds3").removeAttr("onclick");
           $("#deletes3").attr("onclick", "orderaccountdelete(3)")
           $("#organization_name").val("")
           $("#organization_name").text("")
       }
   }


}

//改变审批顺序下样式
function xuanzhonga() {
    var approvalorder= $(".approvalorder");
    var ordermony=$(".ordermony");
    var isapprovalorder =$(".isapprovalorder");
    var approvalli=$("#menu li")
   var approvalli=$("#menu li")
    var approvalordertable=""
  var approveSeqds=""
   for (let i=0;i<approvalli.length;i++) {
       if($("#civil").is(':checked')==true){
           approvalorders=1
           isOrSigndt = 0
           for (let j=0;j<updataapprovalorder.length;j++) {

               if(updataapprovalorder[i]==undefined){
                   approvalordertable='<span>审批顺序</span><input type="text" id="approvalinput"  class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony"><span>订单金额</span>< <span><input class="motyval" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
               }else {
                   if(updataapprovalorder[i].approveSeq==0){
                       approveSeqds=""
                   }else {
                       approveSeqds= updataapprovalorder[i].approveSeq
                   }
                   if(updataapprovalorder[i].isApprove == 20){
                    approvalordertable='<span>审批顺序</span><input type="text" id="approvalinput" value="'+approveSeqds+'" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" checked="true" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony"><span>订单金额</span>< <span><input class="motyval"  style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'
                   }else{
                    approvalordertable='<span>审批顺序</span><input type="text" id="approvalinput" value="'+approveSeqds+'" class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" type="checkbox" onclick="showhdemoy(this)" name="scene" ></span><span  class="ordermony hide"><span>订单金额</span>< <span><input class="motyval" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>'

                   }


               }
           }
           $(approvalorder[i]).html(approvalordertable)

       }else {
           approvalorders=0
           isOrSigndt = ''
           $(approvalorder[i]).html('<span class="approval-orderxu">--</span>')
           $(ordermony[i]).html('<span class="approval-orderxu">--</span>')
           $(isapprovalorder[i]).html('<span class="approval-orderxu">--</span>')
       }
   }


}
function huoqianfn(){
    var approvalorder= $(".approvalorder");
    var ordermony=$(".ordermony");
    var isapprovalorder =$(".isapprovalorder");
    var approvalli=$("#menu li") 
    for (let i=0;i<approvalli.length;i++) {
        console.log($("#huoqian").is(':checked'))
        if($("#huoqian").is(':checked')==true){
            isOrSigndt = 1
            $(approvalorder[i]).html('<span class="approval-orderxu">--</span>')
            $(ordermony[i]).html('<span class="approval-orderxu">--</span>')
            $(isapprovalorder[i]).html('<span class="approval-orderxu">--</span>')
        }else {
            isOrSigndt = ''
            $(approvalorder[i]).html('<span>审批顺序</span><input type="text" id="approvalinput"  class="approval-orderxu approvalinput" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')" maxlength="2"><span class="isapprovalorder"> <span>是否必审</span><input class="checkbox serialnumber" onclick="showhdemoy(this)" type="checkbox" name="scene" ></span><span  class="ordermony"><span>订单金额</span>< <span><input class="motyval" style="width: 64px;" oninput="value=value.replace(/^(0+)|[^\\d]+/g,\'\')">元,跳过本级审批</span> </span> </span>')

        }
    }  
}
//选中数据组成的数组
var accountids={}
var accountmemberId=[]//只用
//获取选中的val
var xuanzhongval={}
var xuanzhongaccount=[]
function accountid(k) {
   if($(k).is(':checked')==true){
       console.log(k)
       //点击勾选的数据保存
       accountids={
           "accountindex":k
       }
       //获取选中的val
       xuanzhongval={
           "accountval":$(k).val()
       }
        accountmemberId.push(accountids)//点击勾选的数据保存
        xuanzhongaccount.push(xuanzhongval)//获取选中的val
    }else {
        //选中取消时去重
        for (let j=0;j<xuanzhongaccount.length;j++) {
            if ($(k).val() == xuanzhongaccount[j].accountval) {
                xuanzhongaccount.splice(j,1)
            }

        }
        for (let i=0;i<xuanzhongaccount.length;i++) {
            if ($(k).val() == $(accountmemberId[i].accountindex)) {
                accountmemberId.splice(i,1)
            }
        }

    }
    console.log(accountmemberId)
}
//删除按钮
function orderaccountdelete(val){
    if(val==1){
        //下单账号删除
        //删除值
        $("#orderaccountadd").html("")
        orderaccountarr.splice(orderaccountarr[0])
        //改变高亮显示
        $("#adds").removeClass("add2-one")
        $("#deletes").removeClass("delete2-one")
        $("#adds").addClass("add-one")
        $("#deletes").addClass("delete-one")
        $("#adds").attr("onclick","orderaccountadd(1)")
        $("#deletes").removeAttr("onclick");
    }else if (val==2) {
        //审批账号删除

                //清空选中数据数组
        for (let j=0;j<accountmemberId.length;j++) {
            for (let i=approvalaccountarr.length - 1;i >= 0;i--) {
                let memberId = approvalaccountarr[i].memberId;
                let memberId2 = $(accountmemberId[j].accountindex).val();
                if (memberId == memberId2){
                    approvalaccountarr.splice(i,1);
                    $(accountmemberId[j].accountindex).parent().remove()
                }

            }
        }
        accountmemberId.splice(0,accountmemberId.length)
        //改变高亮
        var approvalli=$("#menu li")
        if(approvalli.length==0){
            $("#adds2").removeClass("add2-one")
            $("#deletes2").removeClass("delete2-one")
            $("#adds2").addClass("add-one")
            $("#deletes2").addClass("delete-one")
            $("#adds2").attr("onclick","orderaccountadd(2)")
            $("#deletes2").removeAttr("onclick");
        }else {
            $("#adds2").removeClass("add2-one")
            $("#adds2").addClass("add-one")
            $("#adds2").attr("onclick","orderaccountadd(2)")
        }

    }else if (val==3){
        //结算账号删除
        //删除值
        $("#settlementaccount").html("")
        settlementaccountarr.splice(settlementaccountarr[0])
        //改变高亮显示
        //改变高亮显示
        $("#adds3").removeClass("add2-one")
        $("#deletes3").removeClass("delete2-one")
        $("#adds3").addClass("add-one")
        $("#deletes3").addClass("delete-one")
        $("#adds3").attr("onclick","orderaccountadd(3)")
        $("#deletes3").removeAttr("onclick");
    }



}
//修改建立关联
//审批顺序用的数组
var llmap=[]
var newarr=[];
var countnew=[];
var isIng = false;
function establishingcorrelation(){
    newarr=[];
    countnew=[];
    llmap=[];
    if(orderaccountarr==""){
        $.Huimodalalert("请选择下单账号！",2000);
        return false;
    }
    var approveAccountDtos={};
    var approveAccountDtosarr=[];
    var approvalli=$("#menu li");
    var accountnumber=$(".accountnumber2");
    var approvalinput=$(".approvalinput");
    var serialnumber=$(".serialnumber");
    var motyval=$(".motyval");
    var approveSeq="";
    var isApprove="";
    var ordrMoneyimit='';
    var count=0;//定义一个计数变量
    var settleTypedt='';
    $(".webselment").each(function(i,item){
        if($(item).is(':checked')==true){
            settleTypedt=$(item).val();
        }
    })
    for (let i=0;i<approvalli.length;i++) {
        if($(serialnumber[i]).is(':checked')==false){
            count++;
        }
    }
    for (let i=0;i<approvalli.length;i++) {
        if($(approvalinput[i]).val()==undefined){
            approveSeq="0"
        }else {
            approveSeq=$(approvalinput[i]).val()
        }
        if($(motyval[i]).val()==undefined){
            ordrMoneyimit=""
        }else {
            ordrMoneyimit=$(motyval[i]).val()
        }
        if($(approvalinput[i]).val()==""){
            $.Huimodalalert("请填写审批顺序！",2000);
            return false;
        }
        //把审核顺序建立在一个新的llmap数组里
        llmap.push( Number($(approvalinput[i]).val()))
        if($(serialnumber[i]).is(':checked')==true){
            isApprove="20"

        }else {
            if(count==$(serialnumber).length){//如果被没选中的个数等于$(serialnumber)的长度
                isApprove="10"
            }else {
                isApprove="10"
            }
        }
        approveAccountDtos={
            "memberId":$(accountnumber[i]).html(),
            "approveSeq":approveSeq,
            "isApprove":isApprove,
            "isOrSign":isOrSigndt,
            "orderMoneyLimit":ordrMoneyimit,
        }
        approveAccountDtosarr.push(approveAccountDtos)
    }
    //判断审核顺序是否重复
    for(let i = 0;i<llmap.length;i++){
        if(newarr.indexOf(llmap[i]) == -1){
            newarr.push(llmap[i]);
        }else{
            countnew.push(llmap[i]);
        }
    }
    if(countnew.length>0){
        countnew=[];
        $.Huimodalalert("审核顺序不可重复！",2000);
        return false;
    }
console.log(approveAccountDtosarr)
    if(approveAccountDtosarr==""){
        $.Huimodalalert("请选择审批账号！",2000);
        return false;
    }
    if(settlementaccountarr==""){
        $.Huimodalalert("请选择结算账号！",2000);
        return false;
    }
    if(isIng){
        $.Huimodalalert("请求已提交，请勿重复点击！",1000);
        return false;
    }
    isIng = true;
    settlementaccount.settleType=settleTypedt;
    $.ajax({
        url:root.member.updateBindRelation,
        cache: false,  //禁用缓存
        type: "POST",
        dataType:'json',
        contentType: "application/json",
        data: JSON.stringify({
            "accountRelationId":accountRelationId,
            "customerId":customerId,
            "orderAccountDto":orderaccount,//下单对象
            "approveAccountDtos":approveAccountDtosarr,//审核对象
            "settleAccountDto":settlementaccount,//结算对象
        }),
        success: function (data) {
            if (data.errorCode==0){
                isIng = false;
                layer.msg("修改成功",{icon: 6,time:2000},function () {
                    setTimeout(function () {
                        window.parent.chaxun();
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    })
                });
            } else {
                $.Huimodalalert(data.msg,2000);
                isIng = false;
            }

        },
        error: function () {

            $.Huimodalalert('失败！',2000);
            isIng = false;

        }
    });
}
function showhdemoy(e){
    if($(e).is(':checked')){
        $(e).parent().next().removeClass('hide')
    }else{
        $(e).parent().next().addClass('hide')  
    }
}